<template>
  <v-container fluid tag="section">
    <v-row>
      <v-col sm="12" md="12">
        <v-card icon="mdi-clipboard-text" class="px-md-5 py-md-3 pa-xs-0 mt-0">
          <v-card-title>
            <v-row>
              <v-col cols="12" sm="12" md="3">
                <v-text-field v-model="search.name" label="名称"></v-text-field>
              </v-col>
              <v-col cols="12" sm="12" md="8" class="text-left">
                <v-btn
                  regular
                  color="primary"
                  @click="dataInitialize()"
                  class="mr-3"
                >
                  查 询
                </v-btn>
                <v-btn
                  regular
                  color="warning"
                  @click="clearChanged()"
                  class="mr-3"
                >
                  重 置
                </v-btn>
              </v-col>
            </v-row>
          </v-card-title>
          <v-card-text>
            <v-toolbar flat>
              <v-toolbar-title class="d-none d-sm-flex">
                {{ tableTitle }}
              </v-toolbar-title>
              <v-divider
                class="mx-4 d-none d-sm-flex"
                inset
                vertical
              ></v-divider>
              <v-spacer></v-spacer>
              <v-btn color="primary" dark @click="remove(-1)" class="mr-2">
                批量删除
              </v-btn>
              <v-dialog v-model="dialog" persistent max-width="800px">
                <template v-slot:activator="{ on, attrs }">
                  <v-btn
                    color="primary"
                    dark
                    class="mb-2"
                    v-bind="attrs"
                    v-on="on"
                  >
                    添加
                  </v-btn>
                </template>
                <v-card>
                  <v-card-title class="text-left">
                    <span class="text-h3 font-weight-black text-left">
                      {{ formTitle }}
                    </span>
                  </v-card-title>
                  <v-divider></v-divider>
                  <v-card-text class="pt-4">
                    <v-form ref="form">
                      <v-row>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div
                            class="
                              text-h4
                              font-weight-bold
                              form-item-required form-item-label
                            "
                          >
                            菜单名称
                          </div>
                          <v-text-field
                            v-model="editedItem.name"
                            dense
                            :rules="[(v) => !!v || '该项为必填项！']"
                          ></v-text-field>
                        </v-col>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div
                            class="
                              text-h4
                              font-weight-bold
                              form-item-required form-item-label
                            "
                          >
                            菜单编号
                          </div>
                          <v-text-field
                            v-model="editedItem.code"
                            dense
                            :rules="[(v) => !!v || '该项为必填项！']"
                          ></v-text-field>
                        </v-col>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div
                            class="
                              text-h4
                              font-weight-bold
                              form-item-required form-item-label
                            "
                          >
                            菜单层级
                          </div>
                          <v-radio-group
                            v-model="editedItem.type"
                            row
                            dense
                            class="mt-2"
                            :rules="[(v) => !!v || '该项为必填项！']"
                          >
                            <v-radio
                              v-for="(item, index) in dataDicts.typeDicts"
                              :key="index"
                              :value="item.code"
                              :label="item.value"
                              :rules="[(v) => !!v || '该项为必填项！']"
                            ></v-radio>
                          </v-radio-group>
                        </v-col>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div class="text-h4 font-weight-bold form-item-label">
                            重定向
                          </div>
                          <v-text-field
                            v-model="editedItem.redirect"
                            dense
                          ></v-text-field>
                        </v-col>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div
                            class="
                              text-h4
                              font-weight-bold
                              form-item-required form-item-label
                            "
                          >
                            打开方式
                          </div>
                          <v-radio-group
                            v-model="editedItem.openType"
                            row
                            dense
                            class="mt-2"
                            :rules="[(v) => !!v || '该项为必填项！']"
                          >
                            <v-radio
                              v-for="(item, index) in dataDicts.openTypeDicts"
                              :key="index"
                              :value="item.code"
                              :label="item.value"
                            ></v-radio>
                          </v-radio-group>
                        </v-col>
                        <v-col cols="12" class="pb-0">
                          <v-divider></v-divider>
                        </v-col>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div
                            class="
                              text-h4
                              font-weight-bold
                              form-item-required form-item-label
                            "
                          >
                            前端组件
                          </div>
                          <v-text-field
                            v-model="editedItem.component"
                            dense
                          ></v-text-field>
                        </v-col>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div
                            class="
                              text-h4
                              font-weight-bold
                              form-item-required form-item-label
                            "
                          >
                            路由地址
                          </div>
                          <v-text-field
                            v-model="editedItem.router"
                            dense
                          ></v-text-field>
                        </v-col>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div class="text-h4 font-weight-bold form-item-label">
                            内外链地址
                          </div>
                          <v-text-field
                            v-model="editedItem.link"
                            dense
                          ></v-text-field>
                        </v-col>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div class="text-h4 font-weight-bold form-item-label">
                            图标
                          </div>
                          <v-text-field
                            v-model="editedItem.icon"
                            dense
                          ></v-text-field>
                        </v-col>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div class="text-h4 font-weight-bold form-item-label">
                            权重
                          </div>
                          <v-radio-group
                            v-model="editedItem.weight"
                            row
                            dense
                            class="mt-2"
                            :rules="[(v) => !!v || '该项为必填项！']"
                          >
                            <v-radio
                              v-for="(item, index) in dataDicts.weightDicts"
                              :key="index"
                              :value="item.code"
                              :label="item.value"
                            ></v-radio>
                          </v-radio-group>
                        </v-col>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div class="text-h4 font-weight-bold form-item-label">
                            是否可见
                          </div>
                          <v-switch
                            v-model="editedItem.visible"
                            true-value="Y"
                            false-value="N"
                          ></v-switch>
                        </v-col>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div class="text-h4 font-weight-bold form-item-label">
                            排序
                          </div>
                          <v-text-field
                            v-model="editedItem.sort"
                            dense
                          ></v-text-field>
                        </v-col>
                        <v-col cols="12" sm="12" md="6" class="pb-0">
                          <div class="text-h4 font-weight-bold form-item-label">
                            备注
                          </div>
                          <v-text-field
                            v-model="editedItem.remark"
                            dense
                          ></v-text-field>
                        </v-col>
                      </v-row>
                    </v-form>
                  </v-card-text>
                  <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn text @click="close()" color="darken-1"> 取消 </v-btn>
                    <v-btn text @click="save()" color="primary darken-1">
                      保存
                    </v-btn>
                  </v-card-actions>
                </v-card>
              </v-dialog>
            </v-toolbar>

            <tree-data-table
              ref="menuTreeDataTable"
              :headers="headers"
              :selectAll="true"
              :items="items"
              :pagination="paginationOptions"
              :loading="loading"
              :totalItems="total"
              @load="dataInitialize"
            >
              <template slot="row" slot-scope="props">
                <td>{{ props.item.name }}</td>
                <td>{{ typeFilter(props.item.type) }}</td>
                <td>
                  <v-icon small :title="props.item.icon">
                    {{ props.item.icon }}
                  </v-icon>
                </td>
                <td>{{ props.item.component }}</td>
                <td>{{ props.item.router }}</td>
                <td>{{ props.item.sort }}</td>
                <td>
                  <v-icon
                    small
                    @click="editItem(props.item)"
                    title="修改"
                    class="mr-2"
                  >
                    mdi-pencil
                  </v-icon>
                  <v-icon small @click="remove(props.item)" title="删除">
                    mdi-delete
                  </v-icon>
                </td>
              </template>
            </tree-data-table>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import { TreeDataTable } from "@/components/other";

export default {
  name: "MenuIndex",
  components: {
    TreeDataTable,
  },
  data: () => ({
    loading: true,
    selectedTableItems: [], //选中的表格项
    paginationOptions: {},
    total: 0,
    headers: [
      {
        text: "菜单名称",
        value: "name",
        sortable: false,
        width: "160",
      },
      {
        text: "菜单类型",
        value: "type",
        sortable: false,
        width: "100",
      },
      {
        text: "图标",
        value: "icon",
        sortable: false,
        width: "150",
      },
      {
        text: "组件",
        value: "component",
        sortable: false,
        width: "100",
      },
      {
        text: "路由地址",
        value: "router",
        sortable: false,
        width: "150",
      },
      {
        text: "排序",
        value: "sort",
        sortable: true,
        width: "120",
      },
      {
        text: "操作",
        value: "actions",
        sortable: false,
        width: "120",
      },
    ],
    items: [],
    tableTitle: "菜单列表",
    //查询条件
    search: {
      name: "",
    },
    // 表格弹框相关
    dialog: false,
    editedIndex: -1,
    editedItem: {
      id: 0,
      pid: 0,
      pids: "",
      name: "",
      code: "",
      type: 0,
      icon: "",
      router: "",
      component: "",
      permission: "",
      openType: "",
      visible: "",
      link: "",
      redirect: "",
      weight: "",
      sort: "",
      remark: "",
      status: "",
      createdTime: "",
      updatedTime: "",
      createdUserId: "",
      createdUserName: "",
      updatedUserId: "",
      updatedUserName: "",
      isDeleted: "",
    },
    defaultItem: {
      id: 0,
      pid: 0,
      pids: "",
      name: "",
      code: "",
      type: 0,
      icon: "",
      router: "",
      component: "",
      permission: "",
      openType: "",
      visible: "",
      link: "",
      redirect: "",
      weight: "",
      sort: "",
      remark: "",
      status: "",
      createdTime: "",
      updatedTime: "",
      createdUserId: "",
      createdUserName: "",
      updatedUserId: "",
      updatedUserName: "",
      isDeleted: "",
    },
    dataDicts: {
      typeDicts: [], //类型字典
      weightDicts: [], //权重字典
      openTypeDicts: [], //打开方式字典
    },
  }),
  created() {
    //this.dataInitialize();
    //加载字典数据
    this.setDictDatas();
  },
  methods: {
    /**
     * 清空查询条件
     */
    clearChanged() {
      this.search.name = "";
    },
    /**
     * 数据初始化
     */
    dataInitialize(options) {
      var that = this;
      that.loading = true;
      // 这里根据子组件中返回来的分页参数，从而确定传递到服务器端的分页参数
      if (options != undefined) {
        that.paginationOptions = options;
      }
      //设置默认排序列
      if (that.paginationOptions.sortBy.length == 0) {
        that.paginationOptions.sortBy = ["sort"];
      }
      //设置默认排序列的排序方式
      if (that.paginationOptions.sortDesc.length == 0) {
        that.paginationOptions.sortDesc = [false];
      }

      that.request
        .post("/api/menu/page", {
          page: that.paginationOptions.page,
          itemsPerPage: that.paginationOptions.itemsPerPage,
          sortBy: that.paginationOptions.sortBy,
          sortDesc: that.paginationOptions.sortDesc,
          // 查询条件
          name: that.search.name,
        })
        .then((res) => {
          that.total = res.data.total;
          //这里需要将List转为Tree数据
          this.items = that.$common.listToTreeMaterial(
            res.data.records,
            "id",
            "pid"
          );
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * 设置字典数据
     */
    setDictDatas(text) {
      var that = this;
      that.request
        .get("/api/dictType/dropDown", {
          code: "menu_type",
        })
        .then((res) => {
          that.dataDicts.typeDicts = res.data;
        });
      that.request
        .get("/api/dictType/dropDown", {
          code: "menu_weight",
        })
        .then((res) => {
          that.dataDicts.weightDicts = res.data;
        });
      that.request
        .get("/api/dictType/dropDown", {
          code: "open_type",
        })
        .then((res) => {
          that.dataDicts.openTypeDicts = res.data;
        });
    },
    /**
     * 数据删除
     */
    dataDelete(ids) {
      var that = this;
      that.request.post("/api/menu/removeBatchByIds", ids).then((res) => {
        that.$dialog.notify.success("删除成功！", {
          timeout: 2000,
        });
        setTimeout(() => {
          that.dataInitialize();
        }, 2000);
      });
    },
    /**
     * 数据添加或修改
     */
    dataAddOrEdit(item) {
      var that = this;
      let menuItem = Object.assign({}, item);
      delete menuItem.children;
      delete menuItem.depth;
      delete menuItem.leaf;
      delete menuItem.parentNode;
      that.request.post("/api/menu/addOrEdit", menuItem).then((res) => {
        that.$dialog.notify.success("保存成功！", {
          timeout: 2000,
        });
        setTimeout(() => {
          that.dataInitialize();
        }, 2000);
      });
    },
    /**
     * 类型过滤
     */
    typeFilter(type) {
      const values = this.dataDicts.typeDicts.filter(
        (item) => item.code == type
      );
      if (values.length > 0) {
        return values[0].value;
      }
    },
    /**
     * 删除项
     */
    remove(dataItem) {
      var that = this,
        ids = [];
      if (dataItem == -1) {
        // 批量删除
        var items = that.$refs["menuTreeDataTable"].getSelectedTableItems();
        if (items == undefined || items == null || items.length == 0) {
          this.$dialog.notify.warning("请选择要删除的数据项！", {
            position: "top-right",
            timeout: 3000,
          });
          return;
        }
        ids = items.map((item) => {
          return item.id;
        });
      } else {
        ids.push(dataItem.id);
      }
      that.$dialog.confirm({
        text: "确定要删除该项数据吗?",
        title: "警告",
        icon: "mdi-alert-circle",
        actions: [
          {
            text: "取消",
            key: false,
          },
          {
            text: "确定",
            color: "primary",
            key: true,
            handler: function () {
              that.dataDelete(ids);
            },
          },
        ],
      });
    },
    /**
     * 修改项
     */
    editItem(item) {
      this.editedIndex = item.id;
      this.editedItem = Object.assign({}, item);
      this.editedItem.type = this.editedItem.type.toString();
      this.editedItem.openType = this.editedItem.openType.toString();
      this.editedItem.weight = this.editedItem.weight.toString();
      this.dialog = true;
    },
    /**
     * 关闭编辑弹框
     */
    close() {
      this.dialog = false;
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
        this.editedIndex = -1;
      });
    },
    /**
     * 保存
     */
    save() {
      if (this.$refs.form.validate()) {
        if (this.editedIndex > -1) {
          //修改的逻辑
          this.dataAddOrEdit(this.editedItem);
        } else {
          //添加的逻辑
          this.dataAddOrEdit(this.editedItem);
        }
        this.close();
      }
    },
  },
  /**
   * 计算属性
   */
  computed: {
    formTitle() {
      return this.editedIndex === -1 ? "添加" : "修改";
    },
  },
  watch: {
    dialog(val) {
      val || this.close();
    },
  },
};
</script>
